package com.xiaogao.serviceEdu.controller;


import com.xiaogao.commonUtils.Result;
import com.xiaogao.serviceBase.utils.exceptionHandler.XiaoGaoException;
import com.xiaogao.serviceEdu.client.VodClient;
import com.xiaogao.serviceEdu.entity.vo.VideoInfoVo;
import com.xiaogao.serviceEdu.service.EduVideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author 小高
 * @since 2021-06-08
 */
@Api(description="课时管理")
@RestController
@RequestMapping("/serviceEdu/video")
public class EduVideoController {

    @Autowired
    private EduVideoService videoService;

    @Resource
    private VodClient vodClient;

    @ApiOperation(value = "新增课时")
    @PostMapping("/addVideo")
    public Result addVideo(
            @ApiParam(name = "videoInfoVo",value = "课时对象",required = true)
            @RequestBody VideoInfoVo videoInfoVo){
        videoService.addVideoInfo(videoInfoVo);
        return Result.ok();
    }

    @ApiOperation(value = "根据id查询课时信息")
    @GetMapping("/getVideoByid/{id}")
    public Result getVideoByid(
            @ApiParam(name = "id",value = "课时id",required = true)
            @PathVariable String id){

        VideoInfoVo videoInfoVo = videoService.getVideoInfoVoById(id);

        return Result.ok().data("item",videoInfoVo);
    }

    @ApiOperation(value = "更新课时信息")
    @PutMapping("/updateVideoById/{id}")
    public Result updateVideoById(
            @ApiParam(name = "videoInfoVo",value = "课时基本信息",required = true)
            @RequestBody VideoInfoVo videoInfoVo,

            @ApiParam(name = "id",value = "课时id",required = true)
            @PathVariable String id){

        videoService.updateVideoInfoById(videoInfoVo);
        return Result.ok();
    }

    @ApiOperation(value = "根据id删除课时")
    @DeleteMapping("/removeVideoById/{id}")
    public Result removeVideoById(
            @ApiParam(name = "id",value = "课时id",required = true)
            @PathVariable String id){

        // 根据小节id获取视频id，调用方法实现视频删除
        String videoSourceId = videoService.getById(id).getVideoSourceId();

        if (!StringUtils.isEmpty(videoSourceId)){
            Result result = vodClient.removeVideo(videoSourceId);
            if (result.getCode() == 20001){
                throw new XiaoGaoException(20001,"视频删除失败，熔断器");
            }
        }
        videoService.removeVideo(id);
        return Result.ok();
    }
}

